﻿
using LittleBee.Cells;
using LittleBee.JsonRpc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LittleBee.AppServ.JsonRpcInterface
{
	static class AppServJsonRpcObject
	{
		static JsonRpcServer<AppServJsonRpcInterface>? _jsonRpcServer;

		readonly static JsonRpcClient _jsonRpcClientPointerChanged = new JsonRpcClient(65431);

		internal static void Start()
		{
			Task.Run(() =>
			{
				Program.WaitForAppServInitialized();

				_jsonRpcServer = new JsonRpcServer<AppServJsonRpcInterface>(65432);
				_jsonRpcServer.Start();

				_jsonRpcClientPointerChanged.OnJsonRpcException += JsonRpcExceptionHandler;
				_jsonRpcClientPointerChanged.Start();
			});
		}

		private static void JsonRpcExceptionHandler(JsonRpcExceptionEventArg args)
		{
			Console.Write($"JsonRpc exception: {args.ErrorType}: {args.Response}");
		}

		internal static void Stop()
		{
			if (_jsonRpcServer != null)
				_jsonRpcServer.Stop();
			 if (_jsonRpcClientPointerChanged != null)
				_jsonRpcClientPointerChanged.Stop();
		}

		internal static void PushPointerValueHandler(JArray jaPointers)
        {
			_jsonRpcClientPointerChanged!.CallNotifyMethod("UpdatePointer", jaPointers.ToString());
		}
	}
}
